import getUserTempId from "@/utils/userTempId"
import { reqGetUserInfo, reqLogin, reqLogOut } from "@/api"
import { getToken, setToken, removeToken } from "@/utils/token"
const state = {
    userTempId: getUserTempId(),
    token: getToken() || '',
    userInfo: {}
}
const mutations = {
    // 设置token
    setToken(state, payload) {
        state.token = payload.token
        setToken(payload.token)
    },
    // 设置用户信息
    setUserInfo(state, payload) {
        state.userInfo = payload.userInfo
    },
    // 重置token 及用户数据
    logOut(state) {
        state.token = ''
        state.userInfo = {}
        removeToken();
    }
}
const actions = {
    // 获取token
    async getToken({ commit }, payload) {
        try {
            const re = await reqLogin(payload)
            // console.log(re);
            commit('setToken', { token: re.token })
        } catch (e) {

            return Promise.reject(e)
        }
    },

    // 获取用户信息
    async getUserInfo({ commit }) {
        try {
            const re = await reqGetUserInfo();

            commit('setUserInfo', { userInfo: re })
        } catch (e) {
            return Promise.reject(e)

        }
    },
    // 退出登录
    async logOutReq({ commit }) {
        try {
            await reqLogOut();
            commit('logOut')
        } catch (e) { alert(e.message) }
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}